<template>
  <div class="page-wrap">
    <PageTopCover
      :moduleTitle="'影视'"
      :icon="'icon-shipin'"
      :coverImg="getOnlineImgUrl('319')"
      :isMobile="isMobi"
      :modulDesc="'本站所有影视均来源于互联网，仅供学习交流使用，请勿用于任何商业用途！'"
      :isArticle="false"></PageTopCover>
    <div class="page-container-wrap" :class="{ 'm-page-container-wrap': isMobi }">
      <div class="max-width-wrap">
        <div class="page-content-inner">
          <div class="video-list" v-if="state.list.length > 0">
            <div
              class="video-item pointer intersection-observer kbn-custom hover-shadow"
              :data-tip="'想看看 「' + item.title + '」 吗？'"
              @click="handleVideo(item)"
              v-for="(item, index) in state.list"
              :key="index">
              <div class="video-ifarme-wrap">
                <LImg class="video-img" :src="item.cover.includes('http') ? item.cover : getCoverImg(item.cover)" :isUnPreview="true" />
                <i class="iconfont icon-bofang"></i>
              </div>
              <div class="video-item-title text">{{ item.title }}</div>
            </div>
          </div>
          <div class="no-content" v-else>
            <Empty :text="'暂无影视资源，期待您的分享~'" :loadingText="'视频正在拼命加载中...'" :loading="state.loading" />
          </div>

          <LoadingMore
            v-if="store.projectConfig.pageType == 'more'"
            :loading="state.loading"
            :hasMore="state.isMore"
            :length="state.list.length"
            @loadMore="handleLoadMore"></LoadingMore>
          <CustomPage v-else :page="state.page" @change="handlePageChange" :loading="state.loading" scorllTop="video-container-wrap"></CustomPage>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { getZoneList } from '@/api/zone';
import useIntersectionObserver from '@/hooks/useIntersectionObserver';
import useResize from '@/hooks/useResize';
import { useAppStore } from '@/store/app';
import { getOnlineImgUrl } from '@/utils/common';
import { live2dReloadElement, live2dShowMessage } from '@/utils/live2d';
import { onMounted, onUpdated, reactive } from 'vue';

interface VideoItem {
  id: number;
  title: string;
  cover: string;
  bvid: string;
  imgs?: string[];
  remark?: string;
  text?: string;
}

interface PageInfo {
  page: number;
  size: number;
  total: number;
}

interface State {
  loading: boolean;
  isMore: boolean;
  list: VideoItem[];
  page: PageInfo;
}

const store = useAppStore();
const { isMobi } = useResize();
useIntersectionObserver();

const state = reactive<State>({
  loading: false,
  isMore: true,
  list: [],
  page: {
    page: 1,
    size: 10,
    total: 0
  }
});

const getCoverImg = (name: string): string => {
  return new URL(`../../../assets/images/bg/${name}`, import.meta.url).href;
};

const getZoneListFn = (scorllTopCallback?: () => void): Promise<void> => {
  state.loading = true;
  return getZoneList({ ...state.page, type: 1 })
    .then((res: any) => {
      if (res.code === 200) {
        const processData = (item: VideoItem): VideoItem => {
          const imgs = item.imgs?.split(',') || [];
          const cover = imgs[0] ? (import.meta.env.VITE_CURRENT_ENV === 'dev' ? import.meta.env.VITE_DEV_BASE_SERVER + imgs[0] : store.projectConfig.bsServerUrl + imgs[0]) : '';

          return {
            ...item,
            bvid: item.remark || '',
            title: item.text || '',
            cover: cover.includes('http') ? cover : getCoverImg(cover)
          };
        };

        if (store.projectConfig.pageType === 'more') {
          state.list = [...state.list, ...res.data.map(processData)];
        } else {
          state.list = res.data.map(processData);
        }

        state.page.total = res.total;
        state.isMore = state.list.length < res.total;

        scorllTopCallback?.();
      }
    })
    .finally(() => {
      state.loading = false;
    });
};

const handleLoadMore = (): void => {
  state.loading = true;
  state.page.page++;
  getZoneListFn();
};

const handlePageChange = (page: number, size: number, scorllTopCallback?: () => void): void => {
  state.page.page = page;
  state.page.size = size;
  getZoneListFn(scorllTopCallback);
};

const handleVideo = (row: VideoItem): void => {
  const urlPrefix = `${window.location.protocol}//${window.location.host}`;
  window.open(`${urlPrefix}/play/mp4/playing?bvid=${row.bvid}`, '_blank');
};

onMounted(() => {
  getZoneListFn();
  live2dShowMessage('欢迎来到 「我的影视」，快来欣赏吧！');
});

onUpdated(() => {
  live2dReloadElement();
});
</script>

<style lang="scss" scoped>
/* 保持原有样式不变 */
.video-list {
  display: flex;
  flex-wrap: wrap;
  justify-content: space-between;
  .video-item {
    border-radius: var(--border-radius-2);
    width: 435px;
    height: 330px;
    background-color: #fff;
    box-shadow: 0px 0px 10px rgba(0, 0, 0, 0.1);
    margin: 10px;
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    overflow: hidden;
    border: 1px solid #fff;
    &:hover {
      .video-img {
        transform: scale(1.1);
      }
    }
    .video-img {
      transition: all 0.6s ease-in-out;
    }
    .video-ifarme-wrap {
      width: 100%;
      height: 300px;
      overflow: hidden;
      transition: all 1.2s ease-in-out;
      position: relative;
      .iconfont {
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translate(-50%, -50%);
        color: #fff;
        font-size: 50px;
        opacity: 0;
        transition: all 0.3s ease-in-out;
      }
      &:hover {
        .iconfont {
          opacity: 1;
        }
      }
    }
    .video-item-title {
      width: 100%;
      font-size: 16px;
      font-weight: bold;
      text-align: center;
      color: var(--text-color);
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 1;
      overflow: hidden;
      text-overflow: ellipsis;
      height: 30px;
      line-height: 30px;
      background-color: var(--bg-content-color);
      transition: bottom 0.3s ease-in-out;
    }
  }
}
.no-content {
  height: calc(100vh - 450px);
}

.m-page-container-wrap {
  .video-item {
    height: 230px !important;
    width: 100% !important;
    margin: 10px 0 !important;
    .video-ifarme-wrap {
      height: 200px !important;
    }
  }
  .no-content {
    height: calc(100vh - 330px);
  }
}

.dark {
  .video-item {
    border-color: var(--border-color) !important;
  }
}
</style>
